//
//  AddeventView.swift
//  ClassManager
//
//  Created by wqh on 1/27/21.
//

import SwiftUI

struct AddeventView: View {
    @EnvironmentObject var UserData: CoreData
    @Environment(\.presentationMode) var Presentation
    @Environment(\.colorScheme) var _Color: ColorScheme
    @State var isChanging: Bool?
    @State var index: Int?
    @State var teacher: String = ""
    @State var _class: Int = 0
    @State var _repeat = false
    @State var start = Date()
    @State var end: TimeInterval = 5
    @State var state: Int = -1
    @State var ShowPicker = false
    @State var once = false
    @State var ShowAlert = false
    @State var ShowContainedAlert = false
    @State var lastTimeRange: [time] = (5...120).map {return time(id: $0)}
    @State var ShowTimePicker = false
    @State var ShowStartPicker = false
    @State var ShowStatePicker = false
    @State var UIAController = UIAlertController()
//    init (isChanging: Bool? = nil, index: Int? = nil, teacher: String = "", _class: Int = 0, _repeat: Bool = false, start: Date = Date(),
//          end: TimeInterval = 5, state: Int = -1) {
//        self.isChanging = isChanging
//        self.index = index
//        self.teacher = teacher
//        self._class = _class
//        self._repeat = _repeat
//        self.start = start
//        self.end = end
//        self.state = state
//    }
    
    var body: some View {
//        // print(_class)
        return NavigationView {
            Form {
                // MARK: Teacher Name
                Section {
                    HStack {
                        Text("任课老师:")
                        TextField("姓名", text: self.$teacher)
                    }
                }
                
                // MARK: Class Type
                Section {
                    Button(action: {
                        withAnimation(.default) {
                            withAnimation(.default) {
                                self.ShowStartPicker.toggle()
                                UIAController = UIAlertController(title: "课程类型", message: "在此处可以看见您已经添加的课程类型", preferredStyle: .actionSheet)
                                for __class in UserData.classes {
                                    UIAController.addAction(UIAlertAction(title: __class.name, style: .default, handler: { _ in
                                        self._class = __class.id
                                    }))
                                }
                                ShowContainedAlert = true
                            }
                        }
                    }) {
                        HStack {
                            Text("课程类型: \(UserData.classes[self._class].name)")
                            Spacer()
                        }.foregroundColor(_Color == .dark ? .white:.black)
                    }
                    
                    // MARK: Start Time
                    Button(action: {
                        withAnimation(.default) {
                            self.ShowStartPicker.toggle()
                        }
                    }) {
                        HStack {
                            DatePicker("开始时间：", selection: self.$start)
                                .datePickerStyle(CompactDatePickerStyle())
                        }.foregroundColor(_Color == .dark ? .white:.black)
                    }
                    
                    // MARK: Lasting For...
                    Button(action: {
                        withAnimation(.default) {
                            self.ShowStartPicker.toggle()
                            UIAController = UIAlertController(title: "持续时间", message: "持续时间以分钟为单位", preferredStyle: .actionSheet)
                            for time in lastTimeRange {
                                UIAController.addAction(UIAlertAction(title: "\(time.id)", style: .default, handler: { _ in
                                    self.end = TimeInterval(time.id)
                                }))
                            }
                            ShowContainedAlert = true
                        }
                    }) {
                        HStack {
                            Text("持续时间:\(Int(self.end))分钟")
                            Spacer()
                        }.foregroundColor(_Color == .dark ? .white:.black)
                    }
                    
                }
                if isChanging != true {
                    
                    //MARK: Repeatable?
                    Section {
                        Button(action: {
                            withAnimation(.default) {
                                self.ShowStartPicker.toggle()
                                UIAController = UIAlertController(title: "每周重复", message: "打开此选项，下周同一时间重复", preferredStyle: .alert)
                                UIAController.addAction(UIAlertAction(title: "启用", style: .default, handler: { _ in
                                    withAnimation(.default) {
                                        _repeat = true
                                    }
                                }))
                                UIAController.addAction(UIAlertAction(title: "关闭", style: .default, handler: { _ in
                                    withAnimation(.default) {
                                        _repeat = false
                                    }
                                }))
                                ShowContainedAlert = true
                            }
                        }) {
                            Toggle("每周重复", isOn: self.$_repeat)
                                .foregroundColor(_Color == .dark ? .white:.black)
                        }
                        
                        // MARK: Customize state for administrator
                        HStack {
                            Picker("状态:", selection: self.$state) {
                                Text("未签到").tag(-1)
                                Text("已签到").tag(0)
                                Text("逾期").tag(1)
                                Text("已补签").tag(2)
                            }
                        }.foregroundColor(_Color == .dark ? .white:.black)
                    }
                }
                
                Section {
                    HStack {
                        Button(action: {
                            if isEmbedIn(start: start.timeIntervalSince1970, end: start.timeIntervalSince1970 + end*60) {
                                UIAController =  UIAlertController(title: "致命错误", message: "不能同时上两节课哦~", preferredStyle: .alert)
                                UIAController.addAction(UIAlertAction(title: "确定", style: .cancel))
                                self.ShowContainedAlert = true
                                return
                            }
                            RunAfterVierified(skip: true) {
                                if isChanging == true && _repeat {
                                    UserData.repeateventNextWeek(at: index!)
                                }
                                if index == nil && UserData.events.count <= 990 {
                                    UserData.addevent(_class: _class,
                                                       start: start.timeIntervalSince1970,
                                                       end: start.timeIntervalSince1970 + end * 60,
                                                       teacher: teacher, _repeat: self._repeat, state: self.state)
                                }
                                else if index != nil {
                                    UserData.editevent(index: self.index!, _class: _class,
                                                        start: start.timeIntervalSince1970,
                                                        end: start.timeIntervalSince1970 + end * 60,
                                                        teacher: teacher, _repeat: isChanging == true ? false:self._repeat, state: self.state)
                                }
                                else {
                                    self.ShowAlert = true
                                }
                                Presentation.wrappedValue.dismiss()
                            }
                        }) {
                            Text("确定")
                        }
                        Spacer()
                    }
                    .background(SUIAController(showAlert: $ShowContainedAlert, $UIAController))
                    HStack {
                        Button(action: {
                            Presentation.wrappedValue.dismiss()
                        }) {
                            Text("取消")
                        }
                        Spacer()
                    }
                }
            }
            .navigationBarTitle(index == nil ? "添加":(isChanging == true ? "调课":"编辑"))
        }
    }
    
    func isEmbedIn(start: TimeInterval, end: TimeInterval) -> Bool {
        var flag = false
        let duration = start...end
        for _event in UserData.events {
            if _event.id == index || _event.isRemoved {
                continue
            }
            let d: ClosedRange<TimeInterval> = _event.start..._event.end
            if d.contains(start) || d.contains(end) || duration.contains(_event.start) || duration.contains(_event.end) {
                flag = true
            }
        }
        return flag
    }
}

struct OrigButtonSyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        return configuration.label
    }
}

struct time: Identifiable {
    var id: Int
}
